package io.coderyeah.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.coderyeah.basic.Result;
import io.coderyeah.system.domain.Role;
import io.coderyeah.system.mapper.PermissionMapper;
import io.coderyeah.system.service.RoleService;
import io.coderyeah.system.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author coderyeah
 * @description 针对表【t_role】的数据库操作Service实现
 * @createDate 2022-09-21 11:00:07
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Result AddOrModify(Role role) {
        if (null != role.getId()) {
            // 修改角色信息
            roleMapper.updateById(role);
            // 先删除再添加
            deleteById(role.getId());
            addRole(role);
        } else {
            addRole(role);
        }
        return Result.success(null);
    }

    private void addRole(Role role) {
        // 添加角色
        roleMapper.insert(role);
        final Long roleId = role.getId();
        // 添加该角色拥有的菜单
        final List<Long> menus = role.getMenus();
        if (null != menus) {
            roleMapper.addRoleMenu(roleId, menus);
        }
        // 添加该角色拥有的权限
        final List<Long> permissions = role.getPermissions();
        if (null != permissions) {
            permissionMapper.addRolePermission(roleId, permissions);
        }
    }


    @Override
    public Result deleteById(Long id) {
        // 删除角色下的所有菜单
        roleMapper.deleteRoleMenu(id);
        // 删除角色下的所有权限
        roleMapper.deleteRolePermission(id);
        // 删除员工所属的角色
//        roleMapper.deleteRoleEmployee(id);
        // 删除角色
        roleMapper.deleteById(id);
        return Result.success(null);
    }
}




